package com.dkha.task.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.dkha.common.enums.ErrEnum;
import com.dkha.common.enums.SocketEnum;
import com.dkha.common.redis.RedisKeys;
import com.dkha.common.redis.RedisUtils;
import com.dkha.common.util.UtilValidate;
import com.dkha.task.comm.TimerData;
import com.dkha.task.modual.SysUserTokenEntity;
import com.dkha.task.modual.mapper.SysUserTokenDao;
import com.dkha.task.modual.vo.BayonetVO;
import com.dkha.task.modual.vo.ReturnVO;
import com.google.gson.Gson;
import lombok.Data;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocketContral {


	private Session session;
	private Gson gson=new Gson();

    private static CopyOnWriteArraySet<WebSocketContral> webSocketSet=new CopyOnWriteArraySet<WebSocketContral>();
	public static Map<String,WebSocketContral> myMap=new ConcurrentHashMap();

    private RedisUtils redisUtils;
	//此处是解决无法注入的关键
	private static ApplicationContext applicationContext;
	//要注入的service或者dao
	private SysUserTokenDao sysUserTokenDao;

	public static void setApplicationContext(ApplicationContext applicationContext) {
		WebSocketContral.applicationContext = applicationContext;
	}

	@OnOpen
	public void opOpen(Session session)
	{
        redisUtils =applicationContext.getBean(RedisUtils.class);
        this.session=session;
		if(myMap.containsKey(session.getId()))
		{
            try {
                this.session.close();
            } catch (IOException e) {
            }
//            log.error("已经存在");
            return;
		}
		sysUserTokenDao=applicationContext.getBean(SysUserTokenDao.class);
//		String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());
//		SysUserTokenEntity sysUserTokenEntity= null;//sysUserTokenDao.getByToken(token,time);
//		if(UtilValidate.isEmpty(sysUserTokenEntity))
//		{
//		    log.error("token过期");
//            sessionSendMsg(session,gson.toJson(new ReturnVO(ErrEnum.UNAUTHORIZED)));
//            try {
//                this.session.close();
//            } catch (Exception e) {
//            }
//            return;
//        }
//		//广播使用
//        redisUtils.set("token",token);
//        //对应使用
//        redisUtils.set(RedisKeys.getSessionIdKey(session.getId()),token);
//        TimerData.tokens.put(session.getId(),token);
		webSocketSet.add(this);
		myMap.put(session.getId(), this);
//		log.info(session.getId()+"【websocket消息】有新的连接，总数：{},{},{}",webSocketSet.size(),myMap.size(),token);

	}
	@OnClose
	public void onClose()
	{
//		log.info(this.session.getId()+"【websocket消息】连接断开，总数：{},{}",webSocketSet.size(),myMap.size());
        if(TimerData.bayonetMap.containsKey(this.session.getId())) {
            TimerData.bayonetMap.remove(this.session.getId());
        }
		myMap.remove(this.session.getId());
		webSocketSet.remove(this);
//        log.info("关闭成功{},{},{}",webSocketSet.size(),myMap.size(),TimerData.bayonetMap.size());
	}
	@OnMessage
	public void onMessage(String message)
	{
//        log.error("接收数据:{}",message);
	    if(UtilValidate.isEmpty(this.session) || this.session.isOpen()==false){return;}
        if(UtilValidate.isNotEmpty(message))
        {
            ReturnVO returnVO=gson.fromJson(message,ReturnVO.class);
            if(UtilValidate.isNotEmpty(returnVO) && returnVO.getCode().intValue()==ErrEnum.OK.getCode() && returnVO.getCmd().equals(SocketEnum.BAYONET.getCode()))
            {
                if(UtilValidate.isNotEmpty(returnVO.getData()))
                {
                    Map<String,String> myMap=gson.fromJson(gson.toJson(returnVO.getData()),Map.class);
                    if(UtilValidate.isNotEmpty(myMap) && myMap.containsKey("carmeraId"))
                    {
                        TimerData.bayonetMap.put(this.session.getId(), new BayonetVO(-1L,myMap.get("carmeraId")));
//                        log.error("更换摄像头：{}",TimerData.bayonetMap.get(this.session.getId()));
                    }
                }
            }
        }
//	    log.info("【websocket消息】收到客户端消息：{}",message);
	}


    /**
     * 给指定id用户推送信息
     * @param message
     */
    public void sendMessage(String id,String message)
    {
        for(WebSocketContral websocket:webSocketSet)
        {
            if(websocket.session.getId().equals(id))
            {
//                log.info("【websocket消息】给ID={}发送消息，message={}",id,message);
                sessionSendMsg(websocket.session,message);
                break;
            }

        }
    }
    /**
     * 群发消息调用
     * @param message
     */
	public void sendMessage(String message)
	{
		for(WebSocketContral websocket:webSocketSet)
		{
//			log.info("【websocket消息】广播消息，message={}",message);
            sessionSendMsg(websocket.session,message);
		}
	}

    /**
     * 发送消息
     * @param session
     * @param message
     */
	private void sessionSendMsg(Session session,String message)
    {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("socket发送消息错误："+e.getMessage());
        }
    }


}
